package com.neusoft.neps.service.imp;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neusoft.common.domain.Supervisor;
import com.neusoft.interceptor.JWTUtil;
import com.neusoft.neps.mapper.SupervisorMapper;
import com.neusoft.neps.service.SupervisorService;
import com.neusoft.util;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class SupervisorServiceImp extends ServiceImpl<SupervisorMapper, Supervisor> implements SupervisorService {
    @Resource
    private SupervisorMapper supervisorMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private static final Logger log = LoggerFactory.getLogger(SupervisorServiceImp.class);

    @Override
    public int add(Supervisor supervisor) {
        return supervisorMapper.insert(supervisor);
    }

    @Override
    public List<Supervisor> getList() {
        return supervisorMapper.selectList(null);
    }

    //计算年龄
    @Override
    public Map<String, Object> login(Supervisor supervisor) {
        Map<String, Object> map = new HashMap<>();
        try{
            Map params=new HashMap();
            //获取用户登录携带的登录信息（手机号、密码）
            params.put("phoneNumber",supervisor.getPhoneNumber());//参数名是数据库的字段名
            params.put("password",supervisor.getPassword());
            //调用后台的程序查询用户名密码的正确性
            List<Supervisor> userList = supervisorMapper.selectByMap(params);
            if(userList!=null&&userList.size()>0){
                //获取数据库查询到用户信息
                Supervisor user=userList.get(0);
                Map<String, String> payload = new HashMap<>();
                //封装payload,这里面放需要前台未来用来验证的信息
                payload.put("phoneNumber", String.valueOf(user.getPhoneNumber()));
                payload.put("name", user.getName());
                payload.put("password", user.getPassword());
                // 生成token
                String token = JWTUtil.getToken(payload);
                map.put("status", true);
                map.put("msg", "登录成功");
                map.put("token", token); // 响应token，存储在客户端
                //存储todo....redis
                redisTemplate.opsForValue().set(supervisor.getPhoneNumber(), token, 30, TimeUnit.MINUTES);
            }else{
                log.info("用户名或密码有误");
                map.put("status", false);
                map.put("msg", "用户名或密码有误");
            }
        }catch (Exception e) {
            log.info("登录失败...");
            map.put("status", false);
            map.put("msg", "登录失败");
        }
        return map;
    }

    @Override
    public Map<String, Object> register(Map<String,Object> supervisor) {
        Map<String,Object> result = new HashMap<>();
        try {
            Map map = new HashMap<>();
            map.put("phoneNumber",supervisor.get("phoneNumber"));
            List<Supervisor> list = supervisorMapper.selectByMap(map);
//            System.out.println(list.size());
            if (list.size()==0){
                Supervisor supervisor_add = new Supervisor();
                supervisor_add.setPhoneNumber((String) supervisor.get("phoneNumber"));
//                System.out.println(supervisor_add);
                supervisor_add.setName((String) supervisor.get("name"));
//                System.out.println(supervisor_add);
                supervisor_add.setSex(Integer.parseInt((String) supervisor.get("sex")));
//                System.out.println(supervisor_add);
                String password = (String) supervisor.get("password");
                System.out.println(password);
                String md5Hex = DigestUtils.md5DigestAsHex(password.getBytes());
                System.out.println(md5Hex);
                supervisor_add.setPassword(md5Hex);
                System.out.println(supervisor_add);
                supervisor_add.setBirthday((String) supervisor.get("birthday"));
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate date = LocalDate.parse((String)supervisor.get("birthday"),formatter);
                LocalDate current = LocalDate.now();
                int age = util.calculateAge(date,current);
                supervisor_add.setAge(age);
                System.out.println(supervisor_add);
                int if_reg = supervisorMapper.insert(supervisor_add);
                if (if_reg==1){
                    result.put("status",true);
                    result.put("msg","注册成功");
                }else{
                    log.info("注册未成功");
                    result.put("status", false);
                    result.put("msg", "注册失败");
                }
            }else{
                log.info("用户已存在");
                result.put("status", false);
                result.put("msg", "用户已存在");
            }
        }catch (Exception e){
            log.info("注册失败...");
            result.put("status", false);
            result.put("msg", "注册失败");
        }
        return result;
    }
}
